class Solution
{
public:
    string reorderSpaces(string text)
    {
        int originLen = text.size();
        stringstream ss(text);
        vector<string> words;
        int wordsLen = 0;
        string s;
        while (ss >> s)
        {
            wordsLen += s.size();
            words.push_back(s);
        }
        int spaceCount = originLen - wordsLen;
        if (words.size() == 1)
        {
            return words[0] + string(spaceCount, ' ');
        }
        int avergeSpace = spaceCount / (words.size() - 1);
        int remainSpace = spaceCount % (words.size() - 1);
        string result(words[0]);
        string innerSpaces(avergeSpace, ' ');
        for (int i = 1; i < words.size(); ++i)
        {

            result += innerSpaces + words[i];
        }
        result += string(remainSpace, ' ');
        return result;
    }
};